package com.lincoln.gateway.zuul;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对不同域名做不同转发
 *
 * @author lincoln
 */
@Component
public class UrlFilter extends ZuulFilter {
    @Autowired
    ApplicationEventPublisher publisher;

    @Autowired
    RouteLocator routeLocator;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run(){
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        if ("/add".equals(request.getServletPath()) && request.getParameterMap().containsKey("site") && request.getParameterMap().containsKey("path") && request.getParameterMap().containsKey("url") && request.getParameterMap().containsKey("stripPrefix")) {
            String res = ZuulApplication.add(request.getParameter("site"), request.getParameter("path"), request.getParameter("url"), Boolean.parseBoolean(request.getParameter("stripPrefix")));
            HttpServletResponse response = ctx.getResponse();
            try {
                response.getOutputStream().write(res.getBytes());
                response.getOutputStream().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
        if ("/delete".equals(request.getServletPath()) && request.getParameterMap().containsKey("site") && request.getParameterMap().containsKey("path")) {
            String res = ZuulApplication.delete(request.getParameter("site"), request.getParameter("path"));
            HttpServletResponse response = ctx.getResponse();
            try {
                response.getOutputStream().write(res.getBytes());
                response.getOutputStream().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        String url = request.getRequestURL().toString().replaceAll("http://", "");
        if (url.indexOf("/") != -1) {
            url = url.substring(0, url.indexOf("/"));
        }
        MyRouteLocator.url.set(url);
        RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
        publisher.publishEvent(routesRefreshedEvent);
        return null;
    }
}

